package com.windfone.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import org.springframework.context.ApplicationContext;

import com.windfone.service.CommonService;

public class OrderUtil {
	private static Hashtable<String, Integer> seq = new Hashtable<String, Integer>();

	public synchronized static String getOrderSeq(){
		String rtv = "0000";
		String datetimeKey=new SimpleDateFormat("yyyyMMdd").format(new Date());
		if ( seq.keySet().size()==0){
			seq.put(datetimeKey, 0);
		} else {
			if ( seq.get(datetimeKey) == null){
				seq.clear();
				seq.put(datetimeKey, 0);
			} else {
				int order =seq.get(datetimeKey)+1;
				String orderStr = ""+order;
				int len= rtv.length();
				int sub=orderStr.length();
				if ( len-sub>=0){
					rtv = rtv.substring(0,len-sub);
					rtv = rtv+ orderStr;
				}
				else
					rtv = orderStr;
				seq.put(datetimeKey,order);
			}
		}
		rtv = datetimeKey +rtv;
		return rtv;
	}
	public synchronized static String getOrderSeqByDatabase(){

		ApplicationContext ctx=WebVariable.getSpringCtx();
		CommonService commonService=(CommonService)ctx.getBean("commonService"); 
		String rtv = "0000";
		int daySeq = 0;
		String datetimeKey=new SimpleDateFormat("yyyyMMdd").format(new Date());
		daySeq = commonService.getDatabaseDaySeq(Integer.parseInt(datetimeKey));
		int order =daySeq+1;
		String orderStr = ""+order;
		int len= rtv.length();
		int sub=orderStr.length();
		if ( len-sub>=0){
			rtv = rtv.substring(0,len-sub);
			rtv = rtv+ orderStr;
		}else
			rtv = orderStr;
		commonService.setDatabaseDaySeq(order,Integer.parseInt(datetimeKey) );
		rtv = datetimeKey +rtv;
		return rtv;
	}
	public static int getDateInt(){
		 SimpleDateFormat dateformat1=new SimpleDateFormat("yyyyMMdd");
		 String a1=dateformat1.format(new Date());
		 return Integer.parseInt( a1 );
	}
	public static void main(String args[]){
		System.out.println( getDateInt() );
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
		System.out.println( getOrderSeq());
	}
}
